package wang.unclecat.databinding.slice;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.abilityjet.activedata.ActiveData;
import ohos.aafwk.abilityjet.databinding.DataBindingUtil;
import ohos.aafwk.content.Intent;
import ohos.agp.components.ComponentContainer;
import wang.unclecat.databinding.AbilityMainBinding;
import wang.unclecat.databinding.BuildConfig;
import wang.unclecat.databinding.ResourceTable;
import wang.unclecat.databinding.utils.LayoutHelper;
import wang.unclecat.databinding.vm.MainAbilityModel;

import java.io.IOException;
import java.util.Optional;

public class MainAbilitySlice extends AbilitySlice {
    AbilityMainBinding binding;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        try {
            binding = DataBindingUtil.createBinding(ResourceTable.Layout_ability_main, getContext(), BuildConfig.PACKAGE_NAME);
        } catch (IOException e) {
            e.printStackTrace();
        }

        Optional<ComponentContainer> container = LayoutHelper.getUIContent(this);
        if (container.isPresent()) {
            binding.initComponent(container.get());
            binding.setLifecycle(getLifecycle());

            //用new thread 只是为了证明可以在子线程操作model来直接更新ui数据。对，和安卓一样。
            new Thread(new Runnable() {
                @Override
                public void run() {
                    ActiveData<String> title = new ActiveData<>();
                    title.setData("DataBinding Demo");
                    MainAbilityModel model = new MainAbilityModel();
                    model.setTitle(title);
                    binding.setModel(model);
                }
            }).start();
            //end
        }
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
